package com.zrrd.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.reggie.bean.ShoppingCart;
import com.zrrd.reggie.common.ThreadLocalUtil;
import com.zrrd.reggie.mapper.ShoppingCartMapper;
import com.zrrd.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Slf4j
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;


    @Override
    public ShoppingCart addCart(ShoppingCart shoppingCart) {

        //获取用户id
        Long userId = ThreadLocalUtil.getCurrentId();
        shoppingCart.setUserId(userId);
        //查询购物车数据
        QueryWrapper<ShoppingCart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        //查看是菜品还是套餐
        Long dishId = shoppingCart.getDishId();
        if(dishId!=null){
            //菜品
            wrapper.eq("dish_id",dishId);
        }else {
            //套餐
            wrapper.eq("setmeal_id",shoppingCart.getSetmealId());
        }
        //查看数据是否在购物车中
        ShoppingCart cart = shoppingCartMapper.selectOne(wrapper);
        if(cart!=null){
            //修改数量
            Integer number = cart.getNumber();
            cart.setNumber(number+1);
            shoppingCartMapper.updateById(cart);
            return cart;
        }else {
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            //新增数据
            shoppingCartMapper.insert(shoppingCart);
            return shoppingCart;
        }
    }

    @Override
    public ShoppingCart sub(ShoppingCart shoppingCart) {
        QueryWrapper<ShoppingCart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", ThreadLocalUtil.getCurrentId());
        //查看是菜品还是套餐
        Long dishId = shoppingCart.getDishId();
        if(dishId!=null){
            //菜品
            wrapper.eq("dish_id",dishId);
        }else {
            //套餐
            wrapper.eq("setmeal_id",shoppingCart.getSetmealId());
        }
        //查询数量
        ShoppingCart cart = shoppingCartMapper.selectOne(wrapper);
        Integer number = cart.getNumber();
        //数量-1
        cart.setNumber(number-1);
        shoppingCartMapper.updateById(cart);
        if(number==1){
            shoppingCartMapper.deleteById(cart.getId());
        }
        return cart;
    }
}
